﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using TransformerManager.Shared.Helper.HttpParams;
using hc = HandyControl.Controls;

namespace TransformerManager.WPF.Common.Http.Service
{
    public class AccountService : IAccountService
    {
        private readonly HttpRequest _httpRequest;
        public AccountService(HttpRequest httpRequest)
        {
            _httpRequest = httpRequest;
        }

        public async Task<TokenParams> LoginAsync(LoginParams loginParams)
        {
            string url = $"Authenticate/login";
            string body = JsonConvert.SerializeObject(loginParams);
            var responseMsg = await _httpRequest
                .RequestAsync(HttpMethod.Post, url, null, body);
            var content = await responseMsg.Content.ReadAsStringAsync();
            var result = JsonConvert.DeserializeObject<ServiceResponse<TokenParams>>(content);

            if (!result.Success)
            {
                hc.MessageBox.Show(
                    $"{result.Message}",
                    "登录失败",
                    MessageBoxButton.OK,
                    MessageBoxImage.Error);
                return null;
            }

            return result.Data;
        }

        public async Task RegisterAsync(RegisterParams registerParams)
        {
            string url = $"Authenticate/register";
            string body = JsonConvert.SerializeObject(registerParams);
            var responseMsg = await _httpRequest
                .RequestAsync(HttpMethod.Post, url, null, body);
            var content = await responseMsg.Content.ReadAsStringAsync();
            var result = JsonConvert.DeserializeObject<ServiceResponse>(content);
            if (!result.Success)
            {
                hc.MessageBox.Show(
                    $"用户{registerParams.UserName}注册失败, 服务器响应信息:{result.Message}",
                    $"失败",
                    MessageBoxButton.OK,
                    MessageBoxImage.Error);
                return;
            }

            hc.MessageBox.Show(
                $"用户{registerParams.UserName}注册成功",
                "成功",
                MessageBoxButton.OK,
                MessageBoxImage.Information);
        }
    }
}
